/*
 * OrderDao.java
 * 作用：数据访问对象（DAO），负责与数据库中的 `orders` 表进行交互，提供订单的增删改查操作。
 */
package com.campustradingwall.dao;

import com.campustradingwall.model.Order;
import com.campustradingwall.model.Product;
import com.campustradingwall.model.User;
import com.campustradingwall.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {

    /**
     * 创建订单
     * @param order 订单对象
     */
    public void createOrder(Order order) {
        String sql = "INSERT INTO orders (product_id, buyer_id, seller_id, status) VALUES (?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, order.getProductId());
            stmt.setInt(2, order.getBuyerId());
            stmt.setInt(3, order.getSellerId());
            stmt.setString(4, order.getStatus());
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据卖家ID获取接收到的订单
     * @param sellerId 卖家用户ID
     * @return 订单列表
     */
    public List<Order> getReceivedOrdersBySellerId(int sellerId) {
        return getOrdersByUserId(sellerId, "seller");
    }

    /**
     * 根据买家ID获取发送的订单
     * @param buyerId 买家用户ID
     * @return 订单列表
     */
    public List<Order> getSentOrdersByBuyerId(int buyerId) {
        return getOrdersByUserId(buyerId, "buyer");
    }

    /**
     * 更新订单状态
     * @param orderId 订单ID
     * @param status 新状态
     */
    public void updateOrderStatus(int orderId, String status) {
        String sql = "UPDATE orders SET status = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, status);
            stmt.setInt(2, orderId);
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据订单ID获取订单
     * @param orderId 订单ID
     * @return 订单对象，如果未找到则返回null
     */
    public Order getOrderById(int orderId) {
        String sql = "SELECT o.*, p.name as product_name, p.image_url as product_image, " +
                     "buyer.username as buyer_name, buyer.phone as buyer_phone, " +
                     "seller.username as seller_name, seller.phone as seller_phone " +
                     "FROM orders o " +
                     "JOIN products p ON o.product_id = p.id " +
                     "JOIN users buyer ON o.buyer_id = buyer.id " +
                     "JOIN users seller ON o.seller_id = seller.id " +
                     "WHERE o.id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, orderId);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return extractOrderFromResultSet(rs);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据用户ID和角色（买家/卖家）获取订单列表的通用方法
     * @param userId 用户ID
     * @param userRole "buyer" 或 "seller"
     * @return 订单列表
     */
    private List<Order> getOrdersByUserId(int userId, String userRole) {
        List<Order> orders = new ArrayList<>();
        String roleColumn = userRole.equals("buyer") ? "o.buyer_id" : "o.seller_id";
        String sql = "SELECT o.*, p.name as product_name, p.image_url as product_image, " +
                     "buyer.username as buyer_name, buyer.phone as buyer_phone, " +
                     "seller.username as seller_name, seller.phone as seller_phone " +
                     "FROM orders o " +
                     "JOIN products p ON o.product_id = p.id " +
                     "JOIN users buyer ON o.buyer_id = buyer.id " +
                     "JOIN users seller ON o.seller_id = seller.id " +
                     "WHERE " + roleColumn + " = ? ORDER BY o.created_at DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    orders.add(extractOrderFromResultSet(rs));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }

    /**
     * 获取所有订单（管理员用）
     * @return 订单列表
     */
    public List<Order> getAllOrders() {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT o.*, p.name as product_name, p.image_url as product_image, " +
                     "buyer.username as buyer_name, buyer.phone as buyer_phone, " +
                     "seller.username as seller_name, seller.phone as seller_phone " +
                     "FROM orders o " +
                     "JOIN products p ON o.product_id = p.id " +
                     "JOIN users buyer ON o.buyer_id = buyer.id " +
                     "JOIN users seller ON o.seller_id = seller.id " +
                     "ORDER BY o.created_at DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                orders.add(extractOrderFromResultSet(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }

    private Order extractOrderFromResultSet(ResultSet rs) throws SQLException {
        Order order = new Order();
        order.setId(rs.getInt("id"));
        order.setProductId(rs.getInt("product_id"));
        order.setBuyerId(rs.getInt("buyer_id"));
        order.setSellerId(rs.getInt("seller_id"));
        order.setStatus(rs.getString("status"));
        order.setCreatedAt(rs.getTimestamp("created_at"));

        Product product = new Product();
        product.setId(rs.getInt("product_id"));
        product.setName(rs.getString("product_name"));
        product.setImageUrl(rs.getString("product_image"));
        order.setProduct(product);

        User buyer = new User();
        buyer.setId(rs.getInt("buyer_id"));
        buyer.setUsername(rs.getString("buyer_name"));
        buyer.setPhone(rs.getString("buyer_phone"));
        order.setBuyer(buyer);

        User seller = new User();
        seller.setId(rs.getInt("seller_id"));
        seller.setUsername(rs.getString("seller_name"));
        seller.setPhone(rs.getString("seller_phone"));
        order.setSeller(seller);

        return order;
    }
} 